package com.tsinghuabigdata.edu.ddmath.module.neteaseim.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.stetho.common.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.AVChatStateObserver;
import com.netease.nimlib.sdk.avchat.constant.AVChatResCode;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.netease.nimlib.sdk.avchat.constant.AVChatVideoScalingType;
import com.netease.nimlib.sdk.avchat.model.AVChatAudioFrame;
import com.netease.nimlib.sdk.avchat.model.AVChatData;
import com.netease.nimlib.sdk.avchat.model.AVChatOptionalConfig;
import com.netease.nimlib.sdk.avchat.model.AVChatParameters;
import com.netease.nimlib.sdk.avchat.model.AVChatVideoFrame;
import com.netease.nimlib.sdk.avchat.model.AVChatVideoRender;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomInfo;
import com.netease.nimlib.sdk.rts.RTSCallback;
import com.netease.nimlib.sdk.rts.RTSManager2;
import com.netease.nrtc.sdk.NRtcParameters;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.ModuleProxy;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.NimCache;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.base.ui.TFragment;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.education.activity.ChatRoomActivity;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.education.helper.ChatRoomMemberCache;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.education.helper.VideoListener;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.education.util.Preferences;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.permission.MPermission;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.permission.annotation.OnMPermissionDenied;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.permission.annotation.OnMPermissionGranted;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.permission.annotation.OnMPermissionNeverAskAgain;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.permission.util.MPermissionUtil;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.DateUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by hzxuwen on 2016/2/29.
 */
public class ChatRoomFragment extends TFragment implements AVChatStateObserver, View.OnClickListener {
    private final String TAG = "ChatRoomFragment";
    private final int LIVE_PERMISSION_REQUEST_CODE = 100;

    private Activity activity;
    private ChatRoomInfo roomInfo;
    private String roomId;
    private String roomName;
    private String creatorAccount;
    private String shareUrl; // 分享地址

    private boolean disconnected = false; // 是否断网（断网重连用）
    private boolean isPermissionInit = false; // 是否收到其他成员权限
    private boolean isBackLayoutShow = true; // 返回布局是否显示
    private boolean isCreate = false; // 是否是主播

    private VideoListener videoListener;
    private List<String> userJoinedList = new ArrayList<>(); // 已经onUserJoined的用户
    private Map<String, Boolean> permissionMembers = new HashMap<>();
    AVChatVideoRender masterRender; // 主播画布
    public boolean isFragmentInitDone = false;

    /**
     * 聊天室TAB（下）
     */
    private int scrollState;
    private Context context;

    /**
     * 直播区域（上）
     */
    private ViewGroup masterVideoLayout; // 左上，主播显示区域
    private ViewGroup firstRightVideoLayout; // 右上，第一个观众显示区域
    private ViewGroup[] viewLayouts = new ViewGroup[1];

    private FrameLayout mFlTeacherVideo; // 老师播放区域
    private FrameLayout mFlStudentVideo; // 学生播放区域
    private ImageView mIvNetworkStatus; // 网络状况
    private CheckBox mCbVideoPermission; // 视频权限按钮
    private CheckBox mCbAudioPermission; // 音频权限按钮
    private TextView mTvTutorTime; // 在线辅导时间
    private Button mBtnExit; // 退出按钮

    private int time = 0;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String time = (String) msg.obj;
            mTvTutorTime.setText(time);
        }
    };
    private ScheduledExecutorService scheduledExecutorService;


    /**
     * ********************************** 生命周期 **********************************
     */

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.chat_room_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getContext();

        findViews();
        registerObservers(true);
        requestLivePermission();
        isFragmentInitDone = true;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.activity = (ChatRoomActivity) context;
        videoListener = (VideoListener) context;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        registerObservers(false);
        clearChatRoom();
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume()");
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        mTvTutorTime.setText("在线辅导时间 00:00");
        scheduledExecutorService.scheduleWithFixedDelay(
                new ViewPageTask(),
                1,
                1,
                TimeUnit.SECONDS);
    }
    private void registerObservers(boolean register) {
        AVChatManager.getInstance().observeAVChatState(this, register);
    }
    private class ViewPageTask implements Runnable {

        @Override
        public void run() {
            time++;
//            Log.i(TAG, "time=" + time);
            mHandler.obtainMessage(0, DateUtils.timeCalculate(time)).sendToTarget();
            //            mTvTutorTime.setText("在线辅导时间 "+ DateUtils.timeCalculate(time));
        }
    }

    public void onBackPressed() {
        logoutChatRoom();
    }

    public void onKickOut() {
        LogUtil.d(TAG, "chat room do kick out");
        activity.finish();
    }

    private void logoutChatRoom() {
        AlertManager.showCustomDialog(context, "退出在线辅导", "确定", "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                clearChatRoom();
                activity.finish();
            }
        }, null);

    }


    private void clearChatRoom() {
        LogUtil.d(TAG, "chat room do clear");
        AVChatManager.getInstance().leaveRoom(new AVChatCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                LogUtil.d(TAG, "leave channel success");
            }

            @Override
            public void onFailed(int i) {
                LogUtil.d(TAG, "leave channel failed, code:" + i);
            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
        RTSManager2.getInstance().leaveSession(roomId, new RTSCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                LogUtil.d(TAG, "leave rts session success");
            }

            @Override
            public void onFailed(int i) {
                LogUtil.d(TAG, "leave rts session failed, code:" + i);
            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
        permissionMembers.clear();
        userJoinedList.clear();
    }

    /**
     * ********************************** View初始化 **********************************
     */

    private void findViews() {
        // 直播区域
        mFlTeacherVideo = findView(R.id.fl_teacher_video);
        mFlStudentVideo = findView(R.id.fl_student_video);
        mIvNetworkStatus = findView(R.id.iv_network_status);
        mCbVideoPermission = findView(R.id.cb_video_permission);
        mCbAudioPermission = findView(R.id.cb_audio_permission);
        mTvTutorTime = findView(R.id.tv_tutor_time);
        mBtnExit = findView(R.id.btn_exit);
        mBtnExit.setOnClickListener(this);
        mCbVideoPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = mCbVideoPermission.isChecked();
                //// TODO: 2017/3/21 开启视频
                setVideoState();
            }
        });
        mCbAudioPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = mCbAudioPermission.isChecked();
                setAudioState();
            }
        });
        viewLayouts[0] = mFlStudentVideo;
    }


    // 初始化UI
    public void initLiveVideo(ChatRoomInfo roomInfo, String channelName, boolean isCreate, String creator, ModuleProxy moduleProxy) {
        this.roomInfo = roomInfo;
        this.roomId = roomInfo.getRoomId();
        this.roomName = channelName;
        this.isCreate = isCreate;
        creatorAccount = creator;
        AVChatOptionalConfig avChatOptionalParam = new AVChatOptionalConfig();
        int mode = Preferences.getAVChatPip();
        if (mode != -1) {
            LogUtil.i(TAG, "pip mode:" + mode);
            avChatOptionalParam.setLivePIPMode(mode);
        }
        String audioEffect = Preferences.getAudioEffectMode();
        LogUtil.i(TAG, "audio effect ns mode:" + audioEffect);
        avChatOptionalParam.setAudioEffectNSMode(audioEffect);
        if (isCreate) {
            avChatOptionalParam.enableAudienceRole(false);
            avChatOptionalParam.enableLive(true);
            ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, roomInfo.getCreator());
        } else {
            avChatOptionalParam.enableAudienceRole(true);
        }
        AVChatManager.getInstance().joinRoom(roomId, AVChatType.VIDEO, avChatOptionalParam, new AVChatCallback<AVChatData>() {
            @Override
            public void onSuccess(AVChatData avChatData) {
                LogUtil.d(TAG, "join channel success, extra:" + avChatData.getExtra());
                // 设置音量信号监听, 通过AVChatStateObserver的onReportSpeaker回调音量大小
                AVChatParameters avChatParameters = new AVChatParameters();
                avChatParameters.setBoolean(NRtcParameters.KEY_AUDIO_REPORT_SPEAKER, true);
                AVChatManager.getInstance().setParameters(avChatParameters);

                //登录成功，直接开启视频0
                AVChatManager.getInstance().startLive();
                AVChatManager.getInstance().enableAudienceRole(false);

                AVChatManager.getInstance().muteLocalAudio(false);
                AVChatManager.getInstance().muteLocalVideo(false);

                ChatRoomMemberCache.getInstance().setRTSOpen(true);

                videoListener.onAcceptConfirm();
            }

            @Override
            public void onFailed(int i) {
                LogUtil.d(TAG, "join channel failed, code:" + i);
                Toast.makeText(activity, "加入直播房间失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onException(Throwable throwable) {
                Log.d(TAG, "onException: ");
            }
        });
    }


    public void onOnlineStatusChanged(boolean isOnline) {
        //        statusText.setVisibility(isOnline ? View.GONE : View.VISIBLE);
        NIMClient.getService(ChatRoomService.class).fetchRoomInfo(roomId).setCallback(new RequestCallback<ChatRoomInfo>() {
            @Override
            public void onSuccess(ChatRoomInfo chatRoomInfo) {
                roomInfo = chatRoomInfo;
                ((ChatRoomActivity) getActivity()).setRoomInfo(roomInfo);
            }

            @Override
            public void onFailed(int i) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }

    /**************************
     * 音视频权限控制
     ******************************/

    // 权限控制
    private static final String[] LIVE_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO};

    private void requestLivePermission() {
        MPermission.with(ChatRoomFragment.this)
                .addRequestCode(LIVE_PERMISSION_REQUEST_CODE)
                .permissions(LIVE_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(LIVE_PERMISSION_REQUEST_CODE)
    public void onLivePermissionGranted() {
        Toast.makeText(activity, "授权成功", Toast.LENGTH_SHORT).show();
    }

    @OnMPermissionDenied(LIVE_PERMISSION_REQUEST_CODE)
    public void onLivePermissionDenied() {
        List<String> deniedPermissions = MPermission.getDeniedPermissions(this, LIVE_PERMISSIONS);
        String tip = "您拒绝了权限" + MPermissionUtil.toString(deniedPermissions) + "，无法开启直播";
        Toast.makeText(activity, tip, Toast.LENGTH_SHORT).show();
    }

    @OnMPermissionNeverAskAgain(LIVE_PERMISSION_REQUEST_CODE)
    public void onLivePermissionDeniedAsNeverAskAgain() {
        List<String> deniedPermissions = MPermission.getDeniedPermissionsWithoutNeverAskAgain(this, LIVE_PERMISSIONS);
        List<String> neverAskAgainPermission = MPermission.getNeverAskAgainPermissions(this, LIVE_PERMISSIONS);
        StringBuilder sb = new StringBuilder();
        sb.append("无法开启直播，请到系统设置页面开启权限");
        sb.append(MPermissionUtil.toString(neverAskAgainPermission));
        if (deniedPermissions != null && !deniedPermissions.isEmpty()) {
            sb.append(",下次询问请授予权限");
            sb.append(MPermissionUtil.toString(deniedPermissions));
        }

        Toast.makeText(activity, sb.toString(), Toast.LENGTH_LONG).show();
    }

    /**************************
     * 音视频权限控制 end
     ******************************/

    @Override
    public void onTakeSnapshotResult(String account, boolean success, String file) {

    }

    @Override
    public void onConnectionTypeChanged(int netType) {

    }

    @Override
    public void onLocalRecordEnd(String[] files, int event) {

    }

    @Override
    public void onFirstVideoFrameAvailable(String account) {

    }

    @Override
    public void onVideoFpsReported(String account, int fps) {

    }

    /**
     * ************************************ 聊天室 ************************************
     */

    @Override
    public void onJoinedChannel(int i, String s, String s1) {
        LogUtil.d(TAG, "onJoinedChannel, res:" + i);
        if (i != AVChatResCode.JoinChannelCode.OK) {
            Toast.makeText(activity, "joined channel:" + i, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onLeaveChannel() {
        userJoinedList.remove(NimCache.getAccount());
        permissionMembers.remove(NimCache.getAccount());
    }

    @Override
    public void onUserJoined(String s) {
        userJoinedList.add(s);
        permissionMembers.put(s, true);
        onMasterJoin(s);

        //不是主持人，则在这里添加画布
        if (permissionMembers.get(s) && !s.equals(creatorAccount)) {
            onVideoOn(s);
        }

    }

    @Override
    public void onUserLeave(String s, int i) {
        // 用户离开频道，如果是有权限用户，移除下画布
        if (permissionMembers.get(s) && !s.equals(creatorAccount)) {
            onVideoOff(s);
        } else if (s.equals(creatorAccount)) {
            mFlTeacherVideo.removeAllViews();
        }
        videoListener.onUserLeave(s);
        userJoinedList.remove(s);
        permissionMembers.remove(s);
    }

    @Override
    public void onProtocolIncompatible(int i) {

    }

    @Override
    public void onDisconnectServer() {

    }

    @Override
    public void onNetworkQuality(String account, int i) {
        Log.i(TAG, "onNetworkQuality account" + account + "status " + i);
        Log.i(TAG, "NimCache.getAccount()=" + NimCache.getAccount());
        if (account.equals(NimCache.getAccount())) {
            if (i == 0) {
                mIvNetworkStatus.setImageResource(R.drawable.ic_wifi4);
            } else if (i == 1) {
                mIvNetworkStatus.setImageResource(R.drawable.ic_wifi3);
            } else if (i == 2) {
                mIvNetworkStatus.setImageResource(R.drawable.ic_wifi2);
            } else {
                mIvNetworkStatus.setImageResource(R.drawable.ic_wifi1);
            }
        }
    }

    @Override
    public void onCallEstablished() {
        //连接成功后，先把自己加进去
        userJoinedList.add(NimCache.getAccount());
        permissionMembers.put(NimCache.getAccount(), true);
        onVideoOn(NimCache.getAccount());
    }

    @Override
    public void onDeviceEvent(int i, String s) {

    }

    @Override
    public void onFirstVideoFrameRendered(String s) {

    }

    @Override
    public void onVideoFrameResolutionChanged(String s, int i, int i1, int i2) {

    }

    @Override
    public int onVideoFrameFilter(AVChatVideoFrame avChatVideoFrame) {
        return 0;
    }

    @Override
    public int onAudioFrameFilter(AVChatAudioFrame avChatAudioFrame) {
        return 0;
    }

    @Override
    public void onAudioOutputDeviceChanged(int i) {

    }

    @Override
    public void onReportSpeaker(Map<String, Integer> map, int i) {
        videoListener.onReportSpeaker(map);
    }

    @Override
    public void onStartLiveResult(int i) {
    }

    @Override
    public void onStopLiveResult(int i) {
    }

    @Override
    public void onAudioMixingEvent(int i) {

    }


    /**************************** AVChatStateObserver end ****************************/

    /***************************
     * 画布的显示和取消
     **********************************/

    // 主持人进入频道
    private void onMasterJoin(String s) {
        if (userJoinedList != null && userJoinedList.contains(s) && s.equals(creatorAccount)) {
            if (masterRender == null) {
                masterRender = new AVChatVideoRender(getActivity());
            }
            boolean isSetup = setupMasterRender(s, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
            if (isSetup && masterRender != null) {
                addIntoMasterPreviewLayout(masterRender);
                ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, roomInfo.getCreator());
            }
        }
    }

    private boolean setupMasterRender(String s, int mode) {
        boolean isSetup = false;
        try {
            isSetup = AVChatManager.getInstance().setupVideoRender(s, masterRender, false, mode);
        } catch (Exception e) {
            LogUtil.e(TAG, "set up video render error:" + e.getMessage());
            e.printStackTrace();
        }
        return isSetup;
    }

    // 将主持人添加到主持人画布
    private void addIntoMasterPreviewLayout(SurfaceView surfaceView) {
        if (surfaceView.getParent() != null)
            ((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
        mFlTeacherVideo.addView(surfaceView);
        surfaceView.setZOrderMediaOverlay(true);
    }

    // 权限变化
    public void onPermissionChange(List<String> accounts) {
        List<String> oldAccounts = new ArrayList<>();
        if (ChatRoomMemberCache.getInstance().getPermissionMems(roomId) != null) {
            oldAccounts.addAll(ChatRoomMemberCache.getInstance().getPermissionMems(roomId));
        }
        // accounts是新的所有人权限。如果oldaccounts不在这个里面，就remove，在就add
        for (String a : oldAccounts) {
            if (a.equals(roomInfo.getCreator())) {
                continue;
            }
            if (accounts.contains(a)) {
                LogUtil.i(TAG, "on permission change, add:" + a);
                // 新增权限
                ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, a);
                onVideoOn(a);
            } else {
                LogUtil.i(TAG, "on permission change, remove:" + a);
                ChatRoomMemberCache.getInstance().removePermissionMem(roomId, a);
                onVideoOff(a);
                ChatRoomMemberCache.getInstance().setRTSOpen(false);
            }
        }

        accounts.removeAll(oldAccounts);
        for (String a : accounts) {
            ChatRoomMemberCache.getInstance().savePermissionMemberbyId(roomId, a);
            if (a.equals(roomInfo.getCreator())) {
                continue;
            }
            onVideoOn(a);
        }
    }

    // 将有权限的成员添加到画布
    public void onVideoOn(String account) {
        Map<Integer, String> imageMap = ChatRoomMemberCache.getInstance().getImageMap(roomId);
        if (imageMap == null) {
            imageMap = new HashMap<>();
        }

        showView(imageMap, account);

        ChatRoomMemberCache.getInstance().saveImageMap(roomId, imageMap);
    }

    // 显示成员图像
    private void showView(Map<Integer, String> imageMap, String a) {
        Log.i(TAG, "showview creator account:" + roomInfo.getCreator() + ", render account:" + a + "  " + userJoinedList.contains(a) +
        " b2 " + !imageMap.containsValue(a) + "b3 " + (imageMap.size() < 2));
        if (userJoinedList != null && userJoinedList.contains(a)
                && !imageMap.containsValue(a) && imageMap.size() < 2 && !a.equals(creatorAccount)) {
            for (int i = 0; i < 1; i++) {
                if (!imageMap.containsKey(i)) {
                    AVChatVideoRender render = new AVChatVideoRender(getActivity());
                    boolean isSetup = false;
                    try {
                        isSetup = AVChatManager.getInstance().setupVideoRender(a, render, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
                        Log.i(TAG, "setup render, creator account:" + roomInfo.getCreator() + ", render account:" + a + ", isSetup:" + isSetup);
                    } catch (Exception e) {
                        Log.e(TAG, "set up video render error:" + e.getMessage());
                        e.printStackTrace();
                    }
                    if (isSetup && render != null) {
                        imageMap.put(i, a);
                        addIntoPreviewLayout(render, viewLayouts[i]);
                    }
                    break;
                }
            }
        }
    }

    // 添加到成员显示的画布
    private void addIntoPreviewLayout(SurfaceView surfaceView, ViewGroup viewLayout) {
        if (surfaceView == null) {
            return;
        }
        if (surfaceView.getParent() != null)
            ((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
        viewLayout.addView(surfaceView);
        surfaceView.setZOrderMediaOverlay(true);
    }

    // 将被取消权限的成员从画布移除, 并将角色置为初始状态
    public void onVideoOff(String account) {
        Map<Integer, String> imageMap = ChatRoomMemberCache.getInstance().getImageMap(roomId);
        if (imageMap == null) {
            return;
        }
        removeView(imageMap, account);
        resetRole(account);
    }

    // 移除成员图像
    private void removeView(Map<Integer, String> imageMap, String account) {
        Iterator<Map.Entry<Integer, String>> it = imageMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, String> entry = it.next();
            if (entry.getValue().equals(account)) {
                viewLayouts[entry.getKey()].removeAllViews();
                it.remove();
                break;
            }
        }
    }

    // 恢复为观众角色
    private void resetRole(String account) {
        if (account.equals(NimCache.getAccount())) {
            AVChatManager.getInstance().muteLocalAudio(true);
            AVChatManager.getInstance().stopLive();
            AVChatManager.getInstance().enableAudienceRole(true);
            AVChatManager.getInstance().muteLocalAudio(false);
            AVChatManager.getInstance().muteLocalVideo(false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_exit:
                logoutChatRoom();
                break;
        }
    }


    // 设置自己的摄像头是否开启
    private void setVideoState() {
        if (AVChatManager.getInstance().isLocalVideoMuted()) {
            mCbVideoPermission.setChecked(true);
            AVChatManager.getInstance().muteLocalVideo(false);
        } else {
            mCbVideoPermission.setChecked(false);
            AVChatManager.getInstance().muteLocalVideo(true);
        }
    }

    // 设置自己的录音是否开启
    private void setAudioState() {
        if (AVChatManager.getInstance().isLocalAudioMuted()) {
            mCbAudioPermission.setChecked(true);
            AVChatManager.getInstance().muteLocalAudio(false);
        } else {
            mCbAudioPermission.setChecked(false);
            AVChatManager.getInstance().muteLocalAudio(true);
        }
    }
}
